// 微信小程序登录
const loginByWeixin = () => {
	getWeixinCode().then((code) => {
		return uniCloud.callFunction({
			name: 'user-center',
			data: {
				action: 'loginByWeixin',
				params: {
					code
				}
			}
		})
	}).then((res) => {
		if (res.result.code === 0) {
			console.log(res)
			uni.setStorageSync('uni_id_token', res.result.token)
			uni.setStorageSync('uni_id_token_expired', res.result.tokenExpired)
		}
	}).catch((err) => {
		uni.showModal({
			showCancel: false,
			content: '微信登录失败，请稍后再试'
		})
	})
}

// 微信小程序获取code
export const getWeixinCode = () => {
	return new Promise((resolve, reject) => {
		wx.login({
			provider: 'weixin',
			success(res) {
				resolve(res.code)
			},
			fail(err) {
				reject(new Error('微信获取Code失败'))
			}
		})
	})
}
export const getPhone = (obj)=>{
	return new Promise((resolve, reject)=>{
		getphone(obj).then(res=>{
			resolve(JSON.parse(res.data.data.phone))
		},err=>{
			reject(err)
		})
	})
}

export const getIsAuth = (scope) => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scope||'scope.userInfo',
			success: res => {
				resolve(true)
			},
			fail: err => {
				reject(false)
			},
		})
	})
}

export const getUserInfo = () => {
	return new Promise((resolve, reject) => {
		wx.getUserProfile({
			withCredentials: true,
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(new Error('用户信息获取失败'))
			}
		})
	})
}

export const isLogin = (callBack) =>{
	uni.getStorage({
		key: 'userInfo',
		success: function (res) {
			callBack(true)
		},
		fail(err){
			callBack(false)
		}
	});
}

export default {
	getWeixinCode,
	loginByWeixin,
	getPhone
}
